﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace Code4WP7SDK
{
    public class WebRequestService
    {
        public delegate void WebRequestCompletedHandler(object sender, WebRequestCompletedEventArgs e);
        public event WebRequestCompletedHandler WebRequestCompleted;

        /// <summary>
        /// Post 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        public void PostRequest(string url, string data)
        {
            RequestState state = new RequestState();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            state.Request = request;
            state.Data = data;
            request.BeginGetRequestStream(new AsyncCallback(RequestReady), state);
        }
        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        public void GetRequest(string url, string data)
        {
            string getUrl = string.Concat(url, "?", data);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
        }

        public void RequestReady(IAsyncResult asyncResult)
        {
            RequestState state = asyncResult.AsyncState as RequestState;
            HttpWebRequest request = state.Request;
            string data = state.Data;
            using (Stream stream = request.EndGetRequestStream(asyncResult))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(data);
                    writer.Flush();
                }
            }
            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
        }

        public void ResponseReady(IAsyncResult asyncResult)
        {
            HttpWebResponse response;
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            try
            {
                response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                string result = string.Empty;
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        result = reader.ReadToEnd();

                    }
                }
                if (WebRequestCompleted != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            WebRequestCompleted(this, new WebRequestCompletedEventArgs(result));
                        });

                }
            }
            catch
            {
                if (WebRequestCompleted != null)
                {
                    string errorMsg = string.Empty;
                    if (!NetStateHelper.NetWorkIsConnecting())
                    {
                        errorMsg = "no network!";
                    }
                    else
                    {
                        errorMsg = "no response";
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            WebRequestCompleted(this, new WebRequestCompletedEventArgs(new Exception(errorMsg)));
                        });
                }
            }
        }
    }

    public class RequestState
    {
        public HttpWebRequest Request { get; set; }
        public string Data { get; set; }
        public string Files { get; set; }
    }

}
